package com.hang.gymmanager.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.gymmanager.Enum.OrderStatusEnum;
import com.hang.gymmanager.Enum.OrderTypeEnum;
import com.hang.gymmanager.Enum.StatusType;
import com.hang.gymmanager.Enum.TradeStatusType;
import com.hang.gymmanager.entity.AlipayOrderEntity;
import com.hang.gymmanager.entity.OrderEntity;
import com.hang.gymmanager.entity.UserInfoEntity;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.mapper.AlipayOrderMapper;
import com.hang.gymmanager.mapper.OrderMapper;
import com.hang.gymmanager.mapper.UserInfoMapper;
import com.hang.gymmanager.req.AddOrderReq;
import com.hang.gymmanager.service.AlipayOrderService;
import com.hang.gymmanager.service.OrderService;
import com.hang.gymmanager.util.NoUtil;
import com.hang.gymmanager.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/3/30 9:46
 */
/**
 * <p>
 * 支付宝支付订单表 服务实现类
 * </p>
 *
 * @author javgo
 * @since 2024-01-13
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AlipayOrderServiceImpl extends ServiceImpl<AlipayOrderMapper, AlipayOrderEntity> implements AlipayOrderService {

    private final AlipayOrderMapper alipayOrderMapper;
    private final OrderMapper orderMapper;
    private final UserInfoMapper userInfoMapper;

    @Override
    public AlipayOrderEntity createOrder(AddOrderReq req) {
        Integer userId = SecurityUtils.getUserId();
        UserInfoEntity user = userInfoMapper.selectById(userId);
        // 生成订单号
        String orderId = NoUtil.getOrderNo();
        AlipayOrderEntity alipayOrder = new AlipayOrderEntity();
        alipayOrder.setOrderId(orderId);
        // 设置订单标题
        int quantity = RandomUtil.randomInt(1, 10);
        alipayOrder.setSubject("用户:"+userId+"充值金额:"+req.getAccount()+"元");
        // 设置总金额
        alipayOrder.setTotalAmount(req.getAccount());
        // 设置交易状态
        alipayOrder.setTradeStatus(TradeStatusType.WAIT_BUYER_PAY.getCode());
        alipayOrder.setCreateTime(LocalDateTime.now());
        // 由于没有实际业务，这里随便设置产品码和产品名称（根据实际业务需求取舍即可）
        alipayOrder.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayOrder.setProductName("充值现金");
        alipayOrder.setCreateTime(LocalDateTime.now());
        alipayOrderMapper.insert(alipayOrder);
        //执行平台充值逻辑
        OrderEntity order = new OrderEntity();
        order.setMessage("用户:"+userId+"充值金额:"+req.getAccount()+"元，订单号{"+orderId+"}");
        order.setType(OrderTypeEnum.RECHARGE.getValue());
        order.setCreateTime(LocalDateTime.now());
        order.setPrice(req.getAccount());
        order.setUserId(userId);
        order.setUserName(user.getName());
        order.setStatus(OrderStatusEnum.CREATE.getValue());
        orderMapper.insert(order);
        return alipayOrder;
    }

    @Override
    public AlipayOrderEntity getOrderInfo(String orderId) {
        QueryWrapper<AlipayOrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<AlipayOrderEntity> alipayOrders = alipayOrderMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(alipayOrders)) {
            AlipayOrderEntity alipayOrder = alipayOrders.get(0);
            return alipayOrder;
        }
        throw new BusinessException("查询订单失败");
    }

    @Override
    public void paySuccess(String orderId, Integer payMethod) {
        AlipayOrderEntity alipayOrder = new AlipayOrderEntity();
        alipayOrder.setOrderId(orderId);
        alipayOrder.setTradeStatus(TradeStatusType.TRADE_SUCCESS.getCode());
        alipayOrder.setPayMethod(payMethod);
        alipayOrder.setGmtPayment(LocalDateTime.now());
        alipayOrderMapper.updateById(alipayOrder);
        // ... 其他业务逻辑（如恢复锁定库存，扣减真实库存等）
        return;
    }

    @Override
    public void paySuccessByOrderId(String orderId, Integer payMethod) {
        QueryWrapper<AlipayOrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("trade_status", TradeStatusType.WAIT_BUYER_PAY.getCode());
        queryWrapper.eq("status", StatusType.ENABLE);
        List<AlipayOrderEntity> alipayOrders = alipayOrderMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(alipayOrders)) {
            AlipayOrderEntity alipayOrder = alipayOrders.get(0);
            paySuccess(alipayOrder.getOrderId(), payMethod);
        }
    }
}
